import { ref, computed } from 'vue'
import { supabase } from '../../lib/supabase'
import type { MovieDetail, MovieDetailView } from './types'
import type { Comment } from '../../types/ui'
import { useTagDisplay, useTagData } from '../tags'

export const useMovieDetail = () => {
  const { getMovieAllTagsDisplay } = useTagDisplay()
  const { fetchMovieTags, initializeTags } = useTagData()
  
  // 电影详情状态
  const movie = ref<MovieDetail | null>(null)
  const movieDetailView = ref<MovieDetailView | null>(null)
  const comments = ref<Comment[]>([])
  const relatedMovies = ref<MovieDetail[]>([])
  const error = ref<string | null>(null)
  const isLoading = ref(false)

  // 加载电影详情 (使用 movies_view)
  const loadMovieDetailView = async (movieId: number) => {
    try {
      isLoading.value = true
      error.value = null

      const { data, error: fetchError } = await supabase
        .from('movies_view')
        .select('*')
        .eq('id', movieId)
        .single()

      if (fetchError) {
        if (fetchError.code === 'PGRST116') {
          error.value = '电影不存在或已被删除'
        } else {
          throw fetchError
        }
        return
      }

      movieDetailView.value = data
    } catch (err) {
      error.value = err instanceof Error ? err.message : '加载电影详情失败'
      console.error('加载电影详情失败:', err)
    } finally {
      isLoading.value = false
    }
  }

  // 加载电影详情 (使用 movies 表)
  const loadMovieDetail = async (id: number): Promise<MovieDetail> => {
    isLoading.value = true
    
    try {
      // 初始化标签系统
      await initializeTags()
      
      // 首先获取电影基本信息
      const { data: movieData, error: movieError } = await supabase
        .from('movies')
        .select('*')
        .eq('id', id)
        .single()

      if (movieError) {
        console.error('Error loading movie detail:', movieError)
        throw movieError
      }

      // 然后获取上传者信息
      let uploaderInfo = {
        id: '',
        name: '未知用户',
        avatar: undefined
      }

      if (movieData.uploader_id) {
        const { data: userData, error: userError } = await supabase
          .from('user_profiles')
          .select('user_id, name, avatar_url')
          .eq('user_id', movieData.uploader_id)
          .single()

        if (!userError && userData) {
          uploaderInfo = {
            id: userData.user_id, // 使用UUID而不是自增ID
            name: userData.name,
            avatar: userData.avatar_url
          }
        }
      }

      // 获取电影的标签信息
      const movieTags = await fetchMovieTags(id)
      
      // 分离系统标签和用户标签
      const systemTags = movieTags
        .filter(tag => tag.category_name !== 'user_tags')
        .reduce((acc, tag) => {
          if (!acc[tag.category_name]) {
            acc[tag.category_name] = []
          }
          acc[tag.category_name].push(tag.tag_display_name)
          return acc
        }, {} as Record<string, string[]>)
      
      const userTags = movieTags
        .filter(tag => tag.category_name === 'user_tags')
        .map(tag => tag.tag_display_name)

      // 转换数据格式
      const movieDetail: MovieDetail = {
        id: movieData.id,
        title: movieData.title,
        originalTitle: movieData.original_title,
        coverUrl: movieData.cover_url,
        videoUrl: movieData.video_url,
        rating: movieData.rating,
        year: movieData.year,
        duration: movieData.duration,
        genres: systemTags.genre || [],
        description: movieData.description,
        plot: movieData.plot,
        actors: movieData.actors || [],
        director: movieData.director,
        uploader: uploaderInfo,
        views: movieData.views,
        likes: movieData.likes,
        isAi: movieData.is_ai,
        universe: systemTags.universe?.[0] || undefined,
        tags: userTags,
        language: systemTags.language?.[0] || '',
        country: systemTags.country?.[0] || '',
        budget: movieData.budget,
        boxOffice: movieData.box_office,
        awards: Array.isArray(movieData.awards) ? movieData.awards : [],
        trivia: movieData.trivia || [],
        createdAt: movieData.created_at,
        updatedAt: movieData.updated_at
      }
      
      movie.value = movieDetail
      isLoading.value = false
      return movieDetail
    } catch (error) {
      console.error('Error loading movie detail:', error)
      isLoading.value = false
      throw error
    }
  }

  // 加载相关电影
  const loadRelatedMovies = async (movieId: number, limit: number = 6) => {
    try {
      const { data, error: fetchError } = await supabase
        .from('movies_view')
        .select('*')
        .neq('id', movieId)
        .order('rating', { ascending: false })
        .limit(limit)

      if (fetchError) throw fetchError

      // 转换数据格式为 MovieDetail 类型
      const movies: MovieDetail[] = (data || []).map(movie => ({
        id: movie.id,
        title: movie.title,
        originalTitle: movie.original_title,
        coverUrl: movie.cover_url,
        videoUrl: movie.video_url,
        rating: movie.rating,
        year: movie.year,
        duration: movie.duration,
        genres: movie.genres || [],
        description: movie.description,
        plot: movie.plot,
        actors: movie.actors || [],
        director: movie.director,
        uploader: {
          id: movie.uploader_id || '',
          name: '未知用户',
          avatar: undefined
        },
        views: movie.views,
        likes: movie.likes,
        isAi: movie.is_ai,
        universe: movie.universe?.[0] || undefined,
        tags: movie.user_tags || [],
        language: movie.language?.[0] || undefined,
        country: movie.country?.[0] || '',
        budget: movie.budget,
        boxOffice: movie.box_office,
        awards: movie.awards || [],
        trivia: movie.trivia || [],
        createdAt: movie.created_at,
        updatedAt: movie.updated_at
      }))

      relatedMovies.value = movies
    } catch (err) {
      console.error('加载相关电影失败:', err)
      relatedMovies.value = []
    }
  }

  // 加载评论
  const loadComments = async (movieId: number): Promise<Comment[]> => {
    try {
      // 首先获取评论数据
      const { data: commentsData, error } = await supabase
        .from('comments')
        .select('*')
        .eq('movie_id', movieId)
        .is('parent_id', null) // 只获取顶级评论
        .order('created_at', { ascending: false })

      if (error) {
        console.error('Error loading comments:', error)
        return []
      }

      // 获取所有用户ID
      const userIds = [...new Set(commentsData.map(comment => comment.user_id).filter(Boolean))]
      
      // 批量获取用户信息
      let userProfiles: any[] = []
      if (userIds.length > 0) {
        const { data: profilesData, error: profilesError } = await supabase
          .from('user_profiles')
          .select('id, user_id, name, avatar_url, is_ai')
          .in('user_id', userIds)
        
        if (!profilesError && profilesData) {
          userProfiles = profilesData
        }
      }

      // 创建用户信息映射
      const userMap = new Map()
      userProfiles.forEach(profile => {
        userMap.set(profile.user_id, profile)
      })

      // 转换数据格式
      const commentsDataFormatted: Comment[] = commentsData.map((comment) => {
        const userProfile = userMap.get(comment.user_id)
        return {
          id: comment.id,
          userId: comment.user_id,
          user: {
            id: userProfile?.user_id || comment.user_id,
            name: userProfile?.name || '未知用户',
            avatar: userProfile?.avatar_url,
            isAi: userProfile?.is_ai || false
          },
          content: comment.content,
          likes: comment.likes,
          dislikes: comment.dislikes,
          replies: [], // 暂时不加载回复
          createdAt: comment.created_at,
          updatedAt: comment.updated_at
        }
      })
      
      comments.value = commentsDataFormatted
      return commentsDataFormatted
    } catch (error) {
      console.error('Error loading comments:', error)
      return []
    }
  }

  // 获取电影的所有标签显示信息
  const getMovieTagsDisplay = computed(() => {
    if (!movieDetailView.value) return []
    
    return getMovieAllTagsDisplay({
      genres: movieDetailView.value.genres,
      universe: movieDetailView.value.universe[0] || undefined,
      language: movieDetailView.value.language[0] || undefined,
      country: movieDetailView.value.country[0] || undefined,
      tags: movieDetailView.value.user_tags
    })
  })

  // 获取电影的系统标签显示信息
  const getMovieSystemTagsDisplay = computed(() => {
    if (!movieDetailView.value) return []
    
    return getMovieAllTagsDisplay({
      genres: movieDetailView.value.genres,
      universe: movieDetailView.value.universe[0] || undefined,
      language: movieDetailView.value.language[0] || undefined,
      country: movieDetailView.value.country[0] || undefined,
      tags: []
    })
  })

  // 获取电影的用户标签显示信息
  const getMovieUserTagsDisplay = computed(() => {
    if (!movieDetailView.value) return []
    
    return getMovieAllTagsDisplay({
      genres: [],
      tags: movieDetailView.value.user_tags
    })
  })

  return {
    // 状态
    movie,
    movieDetailView,
    comments,
    relatedMovies,
    error,
    isLoading,
    
    // 方法
    loadMovieDetail,
    loadMovieDetailView,
    loadComments,
    loadRelatedMovies,
    
    // 标签显示方法
    getMovieTagsDisplay,
    getMovieSystemTagsDisplay,
    getMovieUserTagsDisplay
  }
}
